const e = require('express');
const Product  = require('../models/product');

exports.getAddProduct = (req, res, next)=>{
    res.render('admin/edit-product',{
        pageTitle:'添加产品',
        path:'/admin/add-product',
        formsCss:true,
        productCss:true,
        editing:false

    })
},

exports.postAddProduct = (req, res, next)=>{
    const {title, imageUrl, price, description} = req.body;
   const product =  new Product(null,title, imageUrl, price, description);
   product.save();
     res.redirect('/')
}

exports.getEditProduct = (req,res, next)=>{
    const editMode = req.query.edit;
    if(!editMode){
        return res.redirect('/');
    }
    const prodId = req.params.id;
    
        Product.findById(prodId, product=>{
            res.render('admin/edit-product',{
                pageTitle:'编辑产品',
                path:'/admin/edit-product',
                editing:editMode,
                product:product
            })
        })
    
   
}

exports.postEditProduct = (req, res, next) =>{
    const prodId = req.body.productId;
    const updatedTitle = req.body.title;
    const updatedPrice = req.body.price;
    const updatedImageUrl = req.body.imageUrl;
    const updateDesc = req.body.description;
    const updatedProduct = new Product(prodId, updatedTitle, updatedPrice, updatedImageUrl, updateDesc)
   updatedProduct.save();
   res.redirect('/admin/products');

}
exports.getProducts = (req, res, next)=>{
    const products = Product.fetchAll(products=>   res.render('admin/products', {
        prods: products,
        pageTitle:'管理商品',
        path: '/admin/products'
    }));
 
}
exports.postDeleteProduct = (req, res, next) =>{
    const prodId = req.body.productId;
    Product.deleteById(prodId);
    res.redirect('/admin/products');
}